<template>
    <el-container style="height: 100vh; border: 1px solid #eee;">
        <!-- 左侧店铺菜单 -->
        <el-aside width="200px" style="background-color: #D3DCE6; overflow-y: auto;">
            <div style="padding: 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #999;">
                <span style="font-weight: bold;">店铺列表</span>
                <el-button type="primary" size="mini" @click="showAddShopDialog">
                    <el-icon><Plus /></el-icon>
                </el-button>
            </div>
            <el-menu
                default-active="0"
                class="el-menu-vertical-demo"
                @select="handleShopSelect"
                background-color="#D3DCE6"
                text-color="#333"
                active-text-color="#fff"
            >
                <el-menu-item
                    v-for="(shop, index) in shopData"
                    :key="shop.id"
                    :index="shop.id.toString()"
                >
                    <template #title>
                        <!-- 店铺logo -->
                        <el-image
                            v-if="shop.logo"
                            :src="shop.logo"
                            fit="cover"
                            style="width: 24px; height: 24px; border-radius: 50%; margin-right: 8px; vertical-align: middle;"
                        ></el-image>
                        <span v-else style="display: inline-block; width: 24px; height: 24px; margin-right: 8px;"></span>

                        <span>{{ shop.shopName }}</span>
                        <span style="margin-left: 10px; font-size: 12px;">
                            <el-tag :type="shop.status === 0 ? 'success' : 'danger'" size="mini">
                                {{ shop.status === 0 ? '营业中' : '已关闭' }}
                            </el-tag>
                        </span>
                    </template>
                </el-menu-item>
            </el-menu>
        </el-aside>

        <!-- 右侧商品管理区域 -->
        <el-container>
            <el-main style="padding: 20px;">
                <!-- 当前店铺信息 -->
                <div v-if="currentShop" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
                        <div style="display: flex; align-items: center;">
                            <!-- 店铺logo -->
                            <el-image
                                v-if="currentShop.logo"
                                :src="currentShop.logo"
                                fit="cover"
                                style="width: 40px; height: 40px; border-radius: 50%; margin-right: 12px;"
                            ></el-image>
                            <h2 style="margin: 0;">{{ currentShop.shopName }}</h2>
                        </div>
                        <div>
                            <el-button type="primary" size="mini" @click="showEditShopDialog(currentShop)" style="margin-right: 5px;">
                                编辑
                            </el-button>
                            <el-button type="danger" size="mini" @click="handleDeleteShop(currentShop.id)">
                                删除
                            </el-button>
                        </div>
                    </div>
                    <div style="color: #666; margin-left: 52px;"> <!-- 偏移量与logo宽度+间距一致 -->
                        <p>店铺状态:
                            <el-tag :type="currentShop.status === 0 ? 'success' : 'danger'">
                                {{ currentShop.status === 0 ? '正在营业' : '关闭' }}
                            </el-tag>
                        </p>
                        <p>开店时间: {{ currentShop.createTime }}</p>
                        <p>店铺描述: {{ currentShop.shopDesc || '无描述' }}</p>
                    </div>
                    <el-button type="info" @click="showDetailUser(currentShop)" style="margin-top: 10px; margin-left: 52px;">
                        查看店铺详情
                    </el-button>
                </div>

                <!-- 商品查询表单 -->
                <el-form :model="productQuery" ref="productFormRef" label-width="auto" label-position="right" style="margin-bottom: 20px; background: #fff; padding: 15px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="商品名称" prop="name">
                                <el-input v-model="productQuery.name" placeholder="请输入商品名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="商品类型" prop="type">
                                <el-input v-model="productQuery.type" placeholder="请输入商品类型" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="商品状态" prop="status">
                                <el-select v-model="productQuery.status" placeholder="请选择状态" clearable>
                                    <el-option label="上架" value="0" />
                                    <el-option label="下架" value="1" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-button type="primary" @click="doProductList" style="margin-right: 10px;">查询</el-button>
                                <el-button type="default" @click="resetProductQuery" style="margin-right: 10px;">重置</el-button>
                                <el-button type="success" @click="showAddDialog">新增商品</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 商品表格 -->
                <el-table
                    :data="currentProducts"
                    border
                    style="width: 100%; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                    empty-text="暂无商品数据"
                >
                    <el-table-column prop="name" label="商品名称" width="200" />
                    <!-- 商品主图列 -->
                    <el-table-column label="商品主图" width="120">
                        <template #default="scope">
                            <el-image
                                v-if="scope.row.mainImg"
                                :src="scope.row.mainImg"
                                :preview-src-list="[scope.row.mainImg]"
                                fit="cover"
                                style="width: 80px; height: 80px; border-radius: 4px;"
                            ></el-image>
                            <span v-else>无图片</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="priceBefore" label="原价" width="100" />
                    <el-table-column prop="priceAfter" label="现价" width="100" />
                    <el-table-column prop="count" label="库存" width="80" />
                    <el-table-column prop="buyEd" label="已售" width="80" />
                    <el-table-column label="状态" width="100">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                                {{ scope.row.status === '0' ? '上架' : '下架' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="类型" width="100" />
                    <el-table-column label="规格信息" min-width="300">
                        <template #default="scope">
                            <div v-for="spec in scope.row.specs" :key="spec.id" style="margin-bottom: 5px;">
                                <strong>{{ spec.specName }}:</strong>
                                <span v-for="(value, index) in spec.values" :key="index">
                                    {{ value.value }}
                                    <template v-if="index !== spec.values.length - 1">、</template>
                                </span>
                            </div>
                            <div v-if="!scope.row.specs || scope.row.specs.length === 0">
                                无规格信息
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button
                                type="primary"
                                size="small"
                                style="margin-right: 5px"
                                @click="handleProductUpdate(scope.row)"
                            >
                                更新
                            </el-button>
                            <el-button
                                type="danger"
                                size="small"
                                @click="handleProductOffline(scope.row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="filteredProducts.length"
                    style="margin-top: 15px; text-align: right"
                />
            </el-main>
        </el-container>
    </el-container>

    <!-- 详情 dialog -->
    <detail-shop ref="detailShopRef"></detail-shop>

    <!-- 新增商品对话框 -->
    <el-dialog title="新增商品" v-model="addDialogVisible" width="800px">
        <el-form :model="newProduct" ref="addProductFormRef" label-width="120px" label-position="top">
            <el-row :gutter="20">
                <!-- 所属店铺 -->
                <el-col :span="12">
                    <el-form-item label="所属店铺" prop="shopId" :rules="[{ required: true, message: '请选择所属店铺', trigger: 'change' }]">
                        <el-select v-model="newProduct.shopId" placeholder="请选择所属店铺">
                            <el-option
                                v-for="shop in shopData"
                                :key="shop.id"
                                :label="`${shop.shopName}(${shop.status === 0 ? '营业中' : '已关闭'})`"
                                :value="shop.id"
                            >
                                <template #default>
                                    <el-image
                                        v-if="shop.logo"
                                        :src="shop.logo"
                                        fit="cover"
                                        style="width: 18px; height: 18px; border-radius: 50%; margin-right: 6px; vertical-align: middle;"
                                    ></el-image>
                                    <span>{{ shop.shopName }}({{ shop.status === 0 ? '营业中' : '已关闭' }})</span>
                                </template>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <!-- 商品名称 -->
                <el-col :span="12">
                    <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
                        <el-input v-model="newProduct.name" placeholder="请输入商品名称" />
                    </el-form-item>
                </el-col>

                <!-- 商品类型 -->
                <el-col :span="12">
                    <el-form-item label="商品类型" prop="type" :rules="[{ required: true, message: '请输入商品类型', trigger: 'change' }]">
                        <el-input v-model="newProduct.type" placeholder="请输入商品类型"/>
                    </el-form-item>
                </el-col>

                <!-- 原价 -->
                <el-col :span="12">
                    <el-form-item label="原价" prop="priceBefore" :rules="[{ required: true, type: 'number', message: '请输入原价', trigger: 'blur' }]">
                        <el-input v-model.number="newProduct.priceBefore" placeholder="请输入原价" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 现价 -->
                <el-col :span="12">
                    <el-form-item label="现价" prop="priceAfter" :rules="[{ required: true, type: 'number', message: '请输入现价', trigger: 'blur' }]">
                        <el-input v-model.number="newProduct.priceAfter" placeholder="请输入现价" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 库存 -->
                <el-col :span="12">
                    <el-form-item label="库存" prop="count" :rules="[{ required: true, type: 'number', message: '请输入库存数量', trigger: 'blur' }]">
                        <el-input v-model.number="newProduct.count" placeholder="请输入库存数量" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 商品主图 -->
                <el-col :span="12">
                    <el-form-item label="商品主图" prop="mainImg">
                        <el-input v-model="newProduct.mainImg" placeholder="请输入商品主图URL" />
                    </el-form-item>
                </el-col>

<!--                &lt;!&ndash; 商品状态 &ndash;&gt;
                <el-col :span="12">
                    <el-form-item label="商品状态" prop="status" :rules="[{ required: true, message: '请选择商品状态', trigger: 'change' }]">
                        <el-select v-model="newProduct.status" placeholder="请选择商品状态">
                            <el-option label="上架" value="0" />
                            <el-option label="下架" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>-->

                <!-- 规格信息编辑区域 -->
                <el-col :span="24">
                    <el-form-item label="规格信息">
                        <el-table :data="newProduct.specs" border style="margin-bottom: 10px;">
                            <el-table-column label="规格名称" width="150">
                                <template #default="scope">
                                    <el-input v-model="scope.row.specName" placeholder="规格名称"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格值" width="470">
                                <template #default="scope">
                                    <div
                                        v-for="(val, index) in scope.row.values"
                                        :key="index"
                                        style="display: inline-flex; align-items: center; margin-right: 8px;"
                                    >
                                        <el-input
                                            v-model="val.value"
                                            placeholder="值"
                                            style="width: 250px; margin-right: 4px;"
                                        ></el-input>
                                        <el-button
                                            type="text"
                                            icon="el-icon-delete"
                                            @click="removeAddSpecValue(scope.row, index)"
                                        >×</el-button>
                                    </div>
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        icon="el-icon-plus"
                                        @click="addAddSpecValue(scope.row)"
                                        class="c1"
                                    >添加值</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        size="mini"
                                        icon="el-icon-delete"
                                        @click="removeAddSpec(scope.row)"
                                    >删除规格</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button
                            type="success"
                            size="mini"
                            icon="el-icon-plus"
                            @click="addAddSpec"
                        >添加规格</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitProduct">确定</el-button>
        </template>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog title="编辑商品" v-model="editDialogVisible" width="800px">
        <el-form :model="editProduct" ref="editProductFormRef" label-width="120px" label-position="top">
            <el-row :gutter="20">
                <!-- 所属店铺 -->
                <el-col :span="12">
                    <el-form-item label="所属店铺" prop="shopId" :rules="[{ required: true, message: '请选择所属店铺', trigger: 'change' }]">
                        <el-select v-model="editProduct.shopId" placeholder="请选择所属店铺">
                            <el-option
                                v-for="shop in shopData"
                                :key="shop.id"
                                :label="`${shop.shopName}(${shop.status === 0 ? '营业中' : '已关闭'})`"
                                :value="shop.id"
                            >
                                <template #default>
                                    <el-image
                                        v-if="shop.logo"
                                        :src="shop.logo"
                                        fit="cover"
                                        style="width: 18px; height: 18px; border-radius: 50%; margin-right: 6px; vertical-align: middle;"
                                    ></el-image>
                                    <span>{{ shop.shopName }}({{ shop.status === 0 ? '营业中' : '已关闭' }})</span>
                                </template>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <!-- 商品名称 -->
                <el-col :span="12">
                    <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
                        <el-input v-model="editProduct.name" placeholder="请输入商品名称" />
                    </el-form-item>
                </el-col>

                <!-- 商品类型 -->
                <el-col :span="12">
                    <el-form-item label="商品类型" prop="type" :rules="[{ required: true, message: '请选择商品类型', trigger: 'change' }]">
                        <el-input v-model="editProduct.type" placeholder="请输入商品类型"/>
                    </el-form-item>
                </el-col>

                <!-- 原价 -->
                <el-col :span="12">
                    <el-form-item label="原价" prop="priceBefore" :rules="[{ required: true, type: 'number', message: '请输入原价', trigger: 'blur' }]">
                        <el-input v-model.number="editProduct.priceBefore" placeholder="请输入原价" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 现价 -->
                <el-col :span="12">
                    <el-form-item label="现价" prop="priceAfter" :rules="[{ required: true, type: 'number', message: '请输入现价', trigger: 'blur' }]">
                        <el-input v-model.number="editProduct.priceAfter" placeholder="请输入现价" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 库存 -->
                <el-col :span="12">
                    <el-form-item label="库存" prop="count" :rules="[{ required: true, type: 'number', message: '请输入库存数量', trigger: 'blur' }]">
                        <el-input v-model.number="editProduct.count" placeholder="请输入库存数量" type="number" />
                    </el-form-item>
                </el-col>

                <!-- 商品主图 -->
                <el-col :span="12">
                    <el-form-item label="商品主图" prop="mainImg">
                        <el-input v-model="editProduct.mainImg" placeholder="请输入商品主图URL" />
                    </el-form-item>
                </el-col>

                <!-- 商品状态 -->
                <el-col :span="12">
                    <el-form-item label="商品状态" prop="status" :rules="[{ required: true, message: '请选择商品状态', trigger: 'change' }]">
                        <el-select v-model="editProduct.status" placeholder="请选择商品状态">
                            <el-option label="上架" value="0" />
                            <el-option label="下架" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <!-- 规格信息 -->
                <el-col :span="24">
                    <el-form-item label="规格信息">
                        <el-table :data="editProduct.specs" border style="margin-bottom: 10px;">
                            <el-table-column label="规格名称" width="150" aria-required="true">
                                <template #default="scope">
                                    <el-input v-model="scope.row.specName" placeholder="规格名称"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格值" width="470">
                                <template #default="scope">
                                    <div
                                        v-for="(val, index) in scope.row.values"
                                        :key="index"
                                        style="display: inline-flex; align-items: center; margin-right: 8px;"
                                    >
                                        <el-input
                                            v-model="val.value"
                                            placeholder="值"
                                            style="width: 250px; margin-right: 4px;"
                                        ></el-input>
                                        <el-button
                                            type="text"
                                            icon="el-icon-delete"
                                            @click="removeSpecValue(scope.row, index)"
                                        >×</el-button>
                                    </div>
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        icon="el-icon-plus"
                                        @click="addSpecValue(scope.row)"
                                        class="c1"
                                    >添加值</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        size="mini"
                                        icon="el-icon-delete"
                                        @click="removeSpec(scope.row)"
                                    >删除规格</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button
                            type="success"
                            size="mini"
                            icon="el-icon-plus"
                            @click="addSpec"
                        >添加规格</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditProduct">确定</el-button>
        </template>
    </el-dialog>

    <!-- 新增店铺对话框 -->
    <el-dialog title="新增店铺" v-model="addShopDialogVisible" width="600px">
        <el-form :model="newShop" ref="addShopFormRef" label-width="120px" label-position="top">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="店铺名称" prop="shopName" :rules="[{ required: true, message: '请输入店铺名称', trigger: 'blur' }]">
                        <el-input v-model="newShop.shopName" placeholder="请输入店铺名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺描述" prop="shopDesc">
                        <el-input v-model="newShop.shopDesc" placeholder="请输入店铺描述" type="textarea" rows="3" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺状态" prop="status" :rules="[{ required: true, message: '请选择店铺状态', trigger: 'change' }]">
                        <el-select v-model="newShop.status" placeholder="请选择店铺状态">
                            <el-option label="营业中" value="0" />
                            <el-option label="已关闭" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺logo" prop="logo">
                        <el-input v-model="newShop.logo" placeholder="请输入店铺logo URL" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="addShopDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddShop">确定</el-button>
        </template>
    </el-dialog>

    <!-- 编辑店铺对话框 -->
    <el-dialog title="编辑店铺" v-model="editShopDialogVisible" width="600px">
        <el-form :model="editShop" ref="editShopFormRef" label-width="120px" label-position="top">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="店铺名称" prop="shopName" :rules="[{ required: true, message: '请输入店铺名称', trigger: 'blur' }]">
                        <el-input v-model="editShop.shopName" placeholder="请输入店铺名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺描述" prop="shopDesc">
                        <el-input v-model="editShop.shopDesc" placeholder="请输入店铺描述" type="textarea" rows="3" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺状态" prop="status" :rules="[{ required: true, message: '请选择店铺状态', trigger: 'change' }]">
                        <el-select v-model="editShop.status" placeholder="请选择店铺状态">
                            <el-option label="营业中" value="0" />
                            <el-option label="已关闭" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="店铺logo" prop="logo">
                        <el-input v-model="editShop.logo" placeholder="请输入店铺logo URL" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="editShopDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditShop">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import axios from "axios";
import DetailShop from "./DetailShop.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 分页参数
const pageNum = ref(1);
const pageSize = ref(5);

// 店铺查询条件
const shop = ref({
  shopName: '',
  status: '', // 0表示正在营业，1表示关闭
  createTime: '',
  shopDesc: ''
});

// 店铺数据（新增logo字段）
const shopData = ref([]);

// 当前选中的店铺
const currentShopId = ref(null);
const currentShop = computed(() => {
  return shopData.value.find(shop => shop.id === currentShopId.value) || null;
});

// 商品查询条件
const productQuery = ref({
  name: '',
  type: '',
  status: ''
});

// 过滤后的商品列表（基于当前店铺和查询条件）
const filteredProducts = computed(() => {
  if (!currentShop.value || !currentShop.value.products) return [];

  return currentShop.value.products.filter(product => {
    if (productQuery.value.name && !product.name.includes(productQuery.value.name)) return false;
    if (productQuery.value.type && !product.type.includes(productQuery.value.type)) return false;
    // 关键修改：将商品状态转为字符串后再与查询条件比较，解决类型不匹配问题
    if (productQuery.value.status !== '' && String(product.status) !== productQuery.value.status) return false;
    return true;
  });
});

// 分页后的商品列表
const currentProducts = computed(() => {
  const startIndex = (pageNum.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredProducts.value.slice(startIndex, endIndex);
});

// 新增商品相关
const addDialogVisible = ref(false);
const addProductFormRef = ref();
const newProduct = ref({
  shopId: null,
  name: '',
  type: '',
  priceBefore: 0,
  priceAfter: 0,
  count: 0,
  buyEd: 0,
  mainImg: '',
  specs: []
});

// 编辑商品相关
const editDialogVisible = ref(false);
const editProductFormRef = ref();
const editProduct = ref({
  id: '',
  shopId: null,
  name: '',
  type: '',
  priceBefore: 0,
  priceAfter: 0,
  count: 0,
  buyEd: 0,
  status: "0",
  mainImg: '',
  specs: []
});

// 新增店铺相关
const addShopDialogVisible = ref(false);
const addShopFormRef = ref();

// 手动实现认证服务功能

import { AuthService } from '@/service/auth.ts'
const authService = new AuthService();
const userId = authService.getUserId();
console.log('User ID:', userId);

const newShop = ref({
  userId: userId, // 固定用户ID，实际应用中应从登录信息获取
  shopName: '',
  shopDesc: '',
  status: 0, // 默认营业中
  logo: ''
});

// 编辑店铺相关
const editShopDialogVisible = ref(false);
const editShopFormRef = ref();
const editShop = ref({
  id: 0,
  userId: userId, // 固定用户ID，实际应用中应从登录信息获取
  shopName: '',
  shopDesc: '',
  status: 0,
  logo: ''
});

// 详情组件相关
const detailShopRef = ref();

// 获取店铺列表（会包含logo字段）
const doList = async () => {
  try {
    const { data } = await axios.get('/api/shop/with-products', {
      params: {
        userId: userId,
        shopName: shop.value.shopName,
        status: shop.value.status, // 0表示正在营业，1表示关闭
        createTime: shop.value.createTime,
        shopDesc: shop.value.shopDesc,
        pageNum: 1,
        pageSize: 100
      }
    });
    shopData.value = data.records || data;
    if (shopData.value.length > 0 && !currentShopId.value) {
      currentShopId.value = shopData.value[0].id;
    }
  } catch (error) {
    console.error("请求失败！原因：", error);
  }
};

// 切换店铺
const handleShopSelect = (shopId) => {
  currentShopId.value = Number(shopId);
  pageNum.value = 1;
};

// 商品查询
const doProductList = () => {
  pageNum.value = 1;
};

// 重置商品查询条件
const resetProductQuery = () => {
  productQuery.value = { name: '', type: '', status: '' };
  pageNum.value = 1;
};

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val;
  pageNum.value = 1;
};
const handleCurrentChange = (val) => {
  pageNum.value = val;
};

// 显示新增商品对话框
const showAddDialog = () => {
  if (!currentShopId.value) {
    ElMessage.warning("请先选择一个店铺");
    return;
  }

  // 检查店铺是否正在营业
  const selectedShop = shopData.value.find(shop => shop.id === currentShopId.value);
  if (selectedShop && selectedShop.status !== 0) {
    ElMessage.warning("只有正在营业的店铺才能新增商品");
    return;
  }

  newProduct.value = {
    shopId: currentShopId.value,
    name: '',
    type: '',
    priceBefore: 0,
    priceAfter: 0,
    count: 0,
    buyEd: 0,
    mainImg: '',
    specs: []
  };
  addDialogVisible.value = true;
};

// 新增商品 - 规格操作
const addAddSpec = () => {
  newProduct.value.specs.push({ specName: "", values: [] });
};
const removeAddSpec = (row) => {
  const index = newProduct.value.specs.findIndex(item => item === row);
  if (index !== -1) newProduct.value.specs.splice(index, 1);
};
const addAddSpecValue = (row) => {
  if (!row.values) row.values = [];
  row.values.push({ value: "" });
};
const removeAddSpecValue = (row, index) => {
  if (row.values && index < row.values.length) row.values.splice(index, 1);
};

// 编辑商品 - 规格操作
const addSpec = () => {
  if (!editProduct.value.specs) editProduct.value.specs = [];
  editProduct.value.specs.push({ specName: "", values: [] });
};
const removeSpec = (row) => {
  const index = editProduct.value.specs.findIndex(item => item === row);
  if (index !== -1) editProduct.value.specs.splice(index, 1);
};
const addSpecValue = (row) => {
  if (!row.values) row.values = [];
  row.values.push({ value: "" });
};
const removeSpecValue = (row, index) => {
  if (row.values && index < row.values.length) row.values.splice(index, 1);
};

// 提交新增商品
const submitProduct = async () => {
  if (!addProductFormRef.value) return;
  try {
    await addProductFormRef.value.validate();

    // 检查店铺是否正在营业
    const selectedShop = shopData.value.find(shop => shop.id === newProduct.value.shopId);
    if (selectedShop && selectedShop.status !== 0) {
      ElMessage.warning("只有正在营业的店铺才能新增商品");
      return;
    }

    if (!Array.isArray(newProduct.value.specs)) newProduct.value.specs = [];
    const { data } = await axios.post('/api/shop/product/upload', newProduct.value);
    if (data.code === 200) {
      ElMessage.success('商品上架成功');
      addDialogVisible.value = false;
      doList();
    } else {
      ElMessage.error(data.message || '商品上架失败');
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('商品上架失败：', error);
      ElMessage.error('商品上架失败，请稍后重试');
    }
  }
};

// 处理商品更新
const handleProductUpdate = (product) => {
  // 检查店铺是否正在营业
  const selectedShop = shopData.value.find(shop => shop.id === product.shopId);
  if (selectedShop && selectedShop.status !== 0) {
    ElMessage.warning("只有正在营业的店铺商品才能编辑");
    return;
  }

  editProduct.value = JSON.parse(JSON.stringify(product));
  editDialogVisible.value = true;
};

// 提交编辑商品
const submitEditProduct = async () => {
  if (!editProductFormRef.value) return;
  try {
    await editProductFormRef.value.validate();

    // 检查店铺是否正在营业
    const selectedShop = shopData.value.find(shop => shop.id === editProduct.value.shopId);
    if (selectedShop && selectedShop.status !== 0) {
      ElMessage.warning("只有正在营业的店铺商品才能编辑");
      return;
    }

    if (!Array.isArray(editProduct.value.specs)) editProduct.value.specs = [];
    const { data } = await axios.put('/api/shop/product/update', editProduct.value);
    if (data.code === 200) {
      ElMessage.success('商品更新成功');
      editDialogVisible.value = false;
      doList();
    } else {
      ElMessage.error(data.message || '商品更新失败');
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('商品更新失败：', error);
      ElMessage.error('商品更新失败，请稍后重试');
    }
  }
};

// 处理商品下架
const handleProductOffline = async (product) => {
  // 检查店铺是否正在营业
  const selectedShop = shopData.value.find(shop => shop.id === product.shopId);
  if (selectedShop && selectedShop.status !== 0) {
    ElMessage.warning("只有正在营业的店铺商品才能删除");
    return;
  }

  try {
    const confirmResult = await ElMessageBox.confirm(
        '确定要删除该商品吗？',
        '删除确认',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );
    if (confirmResult === 'confirm') {
      const { data } = await axios.delete('/api/product', { data: { id: product.id } });
      if (data === 1) {
        ElMessage.success('商品删除成功');
        doList();
      } else {
        ElMessage.error('商品删除失败');
      }
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除失败：', error);
      ElMessage.error('操作失败，请稍后重试');
    }
  }
};

// 查看店铺详情
const showDetailUser = (obj) => {
  detailShopRef.value.handleDetailData(obj);
};

// 显示新增店铺对话框
const showAddShopDialog = () => {
  newShop.value = {
    userId: userId,
    shopName: '',
    shopDesc: '',
    status: 0,
    logo: ''
  };
  addShopDialogVisible.value = true;
};

// 显示编辑店铺对话框
const showEditShopDialog = (shop) => {
  editShop.value = JSON.parse(JSON.stringify(shop));
  editShopDialogVisible.value = true;
};

// 提交新增店铺
const submitAddShop = async () => {
  if (!addShopFormRef.value) return;
  try {
    await addShopFormRef.value.validate();

    const { data } = await axios.post('/api/shop/shopMS', newShop.value);
    if (data.code === 200) {
      ElMessage.success('店铺创建成功');
      addShopDialogVisible.value = false;
      doList();
    } else {
      ElMessage.error(data.message || '店铺创建失败');
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('店铺创建失败：', error);
      ElMessage.error('店铺创建失败，请稍后重试');
    }
  }
};

// 提交编辑店铺
const submitEditShop = async () => {
  if (!editShopFormRef.value) return;
  try {
    await editShopFormRef.value.validate();

    const { data } = await axios.put('/api/shop/shopMS', editShop.value);
    if (data.code === 200) {
      ElMessage.success('店铺更新成功');
      editShopDialogVisible.value = false;
      doList();
    } else {
      ElMessage.error(data.message || '店铺更新失败');
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('店铺更新失败：', error);
      ElMessage.error('店铺更新失败，请稍后重试');
    }
  }
};

// 处理店铺删除
const handleDeleteShop = async (shopId) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
        '确定要删除该店铺吗？删除后店铺内所有商品也将被删除',
        '删除确认',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );
    if (confirmResult === 'confirm') {
      const { data } = await axios.delete(`/api/shop/shopMS/${shopId}`);
      if (data.code === 200) {
        ElMessage.success('店铺删除成功');
        // 如果删除的是当前选中的店铺，需要重置选中状态
        if (currentShopId.value === shopId) {
          currentShopId.value = shopData.value.length > 0 ? shopData.value[0].id : null;
        }
        doList();
      } else {
        ElMessage.error(data.message || '店铺删除失败');
      }
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('店铺删除失败：', error);
      ElMessage.error('店铺删除失败，请稍后重试');
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  doList();
});
</script>


<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
}
.el-main {
    background-color: #F5F7FA;
}
.c1 {
    width: 250px;
}
/* 处理图片加载失败的默认样式 */
.el-image__error {
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>